# -*- coding: utf-8 -*-

import shutil

from utils.pyhelper import *

PACKAGE_NAME = 'MARU_PACKAGE_TEMPLATE'
EXTRA_FILE_NAME = 'MARU_EXTRAS'


def convert_package(project_path: str, mtl_path: str):
    # Load the module from helper.
    rule_module = py_load_from_path(os.path.join(project_path, 'arch', 'package.py'))
    # Get the template list.
    if not hasattr(rule_module, PACKAGE_NAME):
        raise Exception('Please define {} in the package.py file.'.format(PACKAGE_NAME))
    # Extract the package template names.
    package_template = getattr(rule_module, PACKAGE_NAME)
    # Construct the rules.
    file_struct = []
    for key_name in package_template:
        file_struct.append(PYTHON_INDENT + "'{}': [],".format(key_name))
    # Create the template for the file.
    filepath = os.path.join(mtl_path, '{}.py'.format('base'))
    with open(filepath, 'w') as base_file:
        base_file.write(PYTHON_FILE_HEADER)
        base_file.write('\n\n')
        # Construct the OP_FILE definitions.
        base_file.write('OP_FILE = {\n')
        # Loop and write the data.
        base_file.write('\n'.join(file_struct))
        base_file.write('\n}\n')
    # Copy the extra files to MTL.
    if not hasattr(rule_module, EXTRA_FILE_NAME):
        return
    # Start to copy extra files to MTL directory.
    package_extras = getattr(rule_module, EXTRA_FILE_NAME)
    for extra_path in package_extras:
        # Check extra path.
        if not extra_path.endswith('.py'):
            extra_path += '.py'
        # Get the absolute file path.
        source_path = os.path.abspath(os.path.join(project_path, 'arch', extra_path))
        # Copy the source path to destination path.
        destination_path = os.path.abspath(os.path.join(mtl_path, extra_path))
        # Ensure the path is valid.
        destination_dir = os.path.dirname(destination_path)
        os.makedirs(destination_dir, exist_ok=True)
        # Copy the file to destination path.
        shutil.copyfile(source_path, destination_path)
